package com.jiuyin.dianjing.ui.fragment.search;

import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.db.util.helper.SearchHistoryProviderHelper;
import com.jiuyin.dianjing.enums.SearchFragment;
import com.jiuyin.dianjing.event.MsgDispatcher;
import com.jiuyin.dianjing.event.WordMsgEvent;
import com.jiuyin.dianjing.model.SearchHistoryModel;
import com.jiuyin.dianjing.ui.fragment.base.BaseFragment;
import com.nex3z.flowlayout.FlowLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_SEARCH;
import static com.jiuyin.dianjing.constant.HelperConstant.EXTRA_KEY_SEARCH_SUGGEST;

/*
 *
 * 搜索默认界面
 */
public class SearchSuggestFragment extends BaseFragment {
    @BindView(R.id.ll_search_his)
    LinearLayout mLlSearchHis;
    @BindView(R.id.ll_search_hot)
    LinearLayout mLlSearchHot;

    @BindView(R.id.fl_search_hot)
    FlowLayout mFlSearchHot;
    @BindView(R.id.fl_search_his)
    FlowLayout mFlSearchHis;
    List<SearchHistoryModel> mHistoryList;
    private String mType;
    private SearchHistoryProviderHelper mSearchHistoryProviderHelper;

    @Override
    public void fetchData() {

    }

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_search_suggest;
    }

    @Override
    protected void initData() {
        mSearchHistoryProviderHelper = SearchHistoryProviderHelper.getInstance();
        mHistoryList = mSearchHistoryProviderHelper.getDbInfo(getContext());
    }


    @Override
    protected void initView() {
        Bundle bundle = getArguments();
        //搜索建议
        if (null != bundle) {
            ArrayList<String> suggestList = bundle.getStringArrayList(EXTRA_KEY_SEARCH_SUGGEST);
            mType = bundle.getString(KEY_SEARCH);
            addSuggestSearch(suggestList);
        } else {
            hideSearchHot();
        }
        //历史记录
        if (null != mHistoryList) {
            int size = mHistoryList.size();
            for (int i = 0; i < size; i++) {
                doAddSearchHistory(mFlSearchHis, mHistoryList.get(i).getContent());
            }
        }
    }


    @OnClick({R.id.img_phone_clear})
    public void onViewClicked(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.img_phone_clear:
                clearHistory(View.GONE);
                break;
            default:
                break;
        }
    }

    /**
     * 清除历史搜索
     */
    private void clearHistory(int visibility) {
        if (View.GONE == visibility) {
            mLlSearchHis.setVisibility(visibility);
            mFlSearchHis.removeAllViews();
            mSearchHistoryProviderHelper.deleteDb(getContext());
        } else {
            mLlSearchHis.setVisibility(visibility);
        }
    }

    /**
     * 添加历史记录
     *
     * @param flowLayout
     * @param content
     */
    private void doAddSearchHistory(FlowLayout flowLayout, String content) {
        int visibility = mLlSearchHis.getVisibility();
        if (visibility != View.VISIBLE) {
            mLlSearchHis.setVisibility(View.VISIBLE);
        }
        int size = flowLayout.getChildCount();
        int historySize = getResources().getInteger(R.integer.history_max_num);
        if (size < historySize) {
            addHistoryView(flowLayout, content);
        }
    }


    private void addHistoryView(FlowLayout flowLayout, String content) {
        TextView textView = new TextView(getContext());
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        textView.setLayoutParams(params);
        Resources resources = getResources();
        int padding = resources.getDimensionPixelSize(R.dimen.text_view_padding);
        textView.setPadding(padding, padding >> 1, padding, padding >> 1);
        textView.setBackgroundResource(R.drawable.tv_search_bg);
        textView.setMaxEms(resources.getInteger(R.integer.text_view_max_num));
        textView.setEllipsize(TextUtils.TruncateAt.START);
        textView.setText(content);
        textView.setTextColor(Color.WHITE);
        textView.setTag(content);
        textView.setSingleLine();
        textView.setOnClickListener(v -> {
            String keyWold = (String) v.getTag();
            search(keyWold);
        });
        flowLayout.addView(textView);
    }

    /**
     * 从服务器获取建议的列表
     */
    private void addSuggestSearch(ArrayList<String> suggestList) {
        if (null == suggestList) {
            hideSearchHot();
            return;
        }
        int length = suggestList.size();
        if (0 == length) {
            hideSearchHot();
            return;
        }
        for (int i = 0; i < length; i++) {
            TextView textView = new TextView(getContext());
            String content = suggestList.get(i);
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            textView.setLayoutParams(params);
            Resources resources = getResources();
            int padding = resources.getDimensionPixelSize(R.dimen.text_view_padding);
            textView.setPadding(padding, padding >> 1, padding, padding >> 1);
            textView.setBackgroundResource(R.drawable.tv_search_bg);
            textView.setMaxEms(resources.getInteger(R.integer.text_view_max_num));
            textView.setEllipsize(TextUtils.TruncateAt.START);
            textView.setText(content);
            textView.setTextColor(Color.WHITE);
            textView.setSingleLine();
            textView.setTag(content);
            textView.setOnClickListener(v -> {
                String keyWold = (String) v.getTag();
                search(keyWold);
            });
            mFlSearchHot.addView(textView);
        }
    }

    private void search(String content) {
        MsgDispatcher msgDispatcher = new MsgDispatcher(SearchFragment.WORD);
        msgDispatcher.setWordMsgEvent(new WordMsgEvent(content, mType));
        EventBus.getDefault().post(msgDispatcher);
    }

    /**
     * 隐藏llSearchHot界面
     */
    private void hideSearchHot() {
        mLlSearchHot.setVisibility(View.GONE);
    }
}
